package com.data.boot.config;


import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.data.boot.service.MyInotifyEventListener;
import com.den_4.inotify_java.*;
import com.den_4.inotify_java.enums.Event;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.LinkedList;
import java.util.List;


/**
 * 监控数据文件 linux 通过inotify机制实现,监听事件
 * Created by dwk on 2019/6/3.
 */
@Component
public class DataFileMonitor implements ApplicationRunner {
    private static final Log log = LogFactory.get();
    @Value(value = "${data.path}")
    public String dataPath;


    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        try {
            MonitorService monitorService = new MonitorService();
            MyInotifyEventListener listener = new MyInotifyEventListener();
            Event[] events = {Event.Close_Write,
                    Event.Create, Event.Delete, Event.Moved_From, Event.Moved_To, Event.Delete_Self};
            List<String> paths = new LinkedList<>();
            Path startingDir = Paths.get(dataPath);
            SimpleFileVisitor simpleFileVisitor = new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    paths.add(dir.toString());
                    return FileVisitResult.CONTINUE;

                }
            };
            Files.walkFileTree(startingDir, simpleFileVisitor);
            for (String path : paths) {//监听子文件夹
                int wd = monitorService.addWatch(path, events);
                monitorService.addListener(wd, listener);
            }
            log.info("启动 {} 数据文件监听服务....", dataPath);
        } catch (Exception e) {
            log.error("数据文件监听服务启动失败!!!");
            e.printStackTrace();
        }
    }
}
